package com.dupt.web.controller.dingTalk.assemble;

import com.dupt.common.annotation.Log;
import com.dupt.common.core.controller.BaseController;
import com.dupt.common.core.domain.AjaxResult;
import com.dupt.common.core.domain.entity.SysUser;
import com.dupt.common.core.domain.model.LoginUser;
import com.dupt.common.enums.BusinessType;
import com.dupt.common.utils.DateUtils;
import com.dupt.common.utils.DictUtils;
import com.dupt.common.utils.SecurityUtils;
import com.dupt.system.domain.MaterialBorrowReturn;
import com.dupt.system.domain.MaterialDetial;
import com.dupt.system.domain.param.MaterialBorrowReturnParam;
import com.dupt.system.domain.vo.AssemblePlanVo;
import com.dupt.system.domain.vo.MaterialDingTalkVo;
import com.dupt.system.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 组装钉钉Controller
 *
 * @author zhuanyu.sun
 * @date 2025-08-04
 */
@RestController
@RequestMapping("/assemble/dingTalk")
public class AssembleDingTalkController extends BaseController {

    @Autowired
    private IAssembleDingTalkService assembleDingTalkService;

    @Autowired
    private IMaterialDingTalkService materialDingTalkService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IMaterialDetialService materialDetialService;

    @Autowired
    private IMaterialBorrowReturnService materialBorrowReturnService;

    /**
     * 钉钉查询组装计划
     */
    @GetMapping("/list/{userId}")

    public AjaxResult list(@PathVariable("userId") String userId)
    {
        // 在Controller方法开头添加认证逻辑
        SysUser user = sysUserService.selectUserByDingTalkId(userId); // 根据钉钉ID查询系统用户
        if (user == null) {
            return error("用户未同步到系统");
        }
        // 手动设置当前登录用户
        LoginUser loginUser = new LoginUser(user, null);
        SecurityContextHolder.getContext().setAuthentication(
                new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities())
        );

        List<AssemblePlanVo> list = assembleDingTalkService.selectAssemblePlanListOfDingTalk();
        return success(list);
    }

    /**
     * 查询物料明细列表
     */
//    @GetMapping("/myself/{userId}")
//    public AjaxResult list(@PathVariable("userId") String userId)
//    {
//        List<MaterialDingTalkVo> list = materialDingTalkService.selectMaterialDingTalkByborrowerId(userId);
//        return success(list);
//    }

    /**
     * 根据内码，序列号，查询物料
     * @param materialInnerCode 物料内码
     * @param serialNo 序列号
     * @param materialInnerCode 物料内
     * @return
     */
    @GetMapping("/{materialInnerCode}/{serialNo}/{userId}")
    public AjaxResult getInfo(@PathVariable("materialInnerCode") String materialInnerCode,@PathVariable("serialNo") String serialNo,@PathVariable("userId") String userId) {
        try {
            MaterialDingTalkVo materialDingTalkVo = materialDingTalkService.selectMaterialDingTalkByInnerCodeAndSerialNo(materialInnerCode,serialNo);
            if(materialDingTalkVo!=null) {
                //不是在用也不是借用，不允许借用归还
                if (!"在库".equals(materialDingTalkVo.getStatus()) && !"借用".equals(materialDingTalkVo.getStatus())) {
                    materialDingTalkVo.setCurrentStatus(2);//2:不允许借用
                    return success(materialDingTalkVo);
                }
                //状态为借用，判断是否为自己，是则显示归还，不是则不允许借用
                else if ("借用".equals(materialDingTalkVo.getStatus())) {
                    //如果是自己，则显示归还信息
                    if (materialDingTalkVo.getBorrowerId().equals(userId)) {
                        materialDingTalkVo.setCurrentStatus(1);//1:归还
                    } else {
                        materialDingTalkVo.setCurrentStatus(2);//2:不允许借用
                    }
                }else {
                    materialDingTalkVo.setCurrentStatus(0);//0：允许借用
                }
                return success(materialDingTalkVo);
            }
            return error("物料不存在，请联系管理员。");
        } catch (Exception e) {
            e.printStackTrace();
            return error("物料查询失败，请联系管理员。");
        }
    }

    /**
     * 新增借用归还信息
     */
//    @Log(title = "组装", businessType = BusinessType.INSERT)
//    @PostMapping
//    public AjaxResult add(@RequestBody MaterialBorrowReturnParam materialBorrowReturnParam)
//    {
//        // 在Controller方法开头添加认证逻辑
//        String ddUserId = materialBorrowReturnParam.getBorrowerId(); // 从小程序端传递的钉钉用户ID
//        SysUser user = sysUserService.selectUserByDingTalkId(ddUserId); // 根据钉钉ID查询系统用户
//        if (user == null) {
//            return error("用户未同步到系统");
//        }
//        // 手动设置当前登录用户
//        LoginUser loginUser = new LoginUser(user, null);
//        SecurityContextHolder.getContext().setAuthentication(
//                new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities())
//        );
//
//        //1.根据内码、序列号查询物料信息
//        MaterialDetial detial = new MaterialDetial();
//        BeanUtils.copyProperties(materialBorrowReturnParam,detial);
//        detial.setStatus(DictUtils.getDictValue("sys_material_status","在库"));
//        detial.setDelFlag("0");
//        List<MaterialDetial> detialList = materialDetialService.selectMaterialDetialList(detial);
//        if(detialList.size()>0){
//            //2.保存借用信息
//            MaterialBorrowReturn materialBorrowReturn = new MaterialBorrowReturn();
//            BeanUtils.copyProperties(materialBorrowReturnParam,materialBorrowReturn);
//            materialBorrowReturn.setMaterialId(detialList.get(0).getMaterialDetialId());
//            materialBorrowReturn.setBorrowTime(DateUtils.getNowDate());
//            materialBorrowReturn.setIsReturn(0);
//            materialBorrowReturn.setCreateBy(SecurityUtils.getLoginUser().getUsername());
//            materialBorrowReturn.setCreateTime(DateUtils.getNowDate());
//            materialDingTalkService.insertMaterialBorrowReturn(materialBorrowReturn);
//            //3.修改物料信息
//            MaterialDetial materialDetial = detialList.get(0);
//            materialDetial.setStatus(DictUtils.getDictValue("sys_material_status","借用"));
//            materialDetial.setCurrentPos(materialBorrowReturnParam.getBorrowBy());
//            materialDetial.setUpdateTime(DateUtils.getNowDate());
//            materialDetial.setUpdateBy(SecurityUtils.getLoginUser().getUsername());
//            materialDetialService.updateMaterialDetial(materialDetial);
//            return success("借用成功");
//        }
//        return error("当前物料不存在，请联系管理员。");
//    }

    /**
     * 归还
     */
//    @PostMapping("/return")
//    public AjaxResult returnMaterial(@RequestBody MaterialBorrowReturnParam materialBorrowReturnParam)
//    {
//        // 在Controller方法开头添加认证逻辑
//        String ddUserId = materialBorrowReturnParam.getBorrowerId(); // 从小程序端传递的钉钉用户ID
//        SysUser user = sysUserService.selectUserByDingTalkId(ddUserId); // 根据钉钉ID查询系统用户
//        if (user == null) {
//            return error("用户未同步到系统");
//        }
//        // 手动设置当前登录用户
//        LoginUser loginUser = new LoginUser(user, null);
//        SecurityContextHolder.getContext().setAuthentication(
//                new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities())
//        );
//        //根据借用ID查询借用信息
//        MaterialBorrowReturn materialBorrowReturn = materialBorrowReturnService.selectMaterialBorrowReturnByMaterialBorrowId(materialBorrowReturnParam.getMaterialBorrowId());
//        if(materialBorrowReturn==null){
//            return error("当前借用信息不存在，请联系管理员。");
//        }
//        materialBorrowReturn.setReturnTime(DateUtils.getNowDate());
//        materialBorrowReturn.setUpdateBy(SecurityUtils.getLoginUser().getUsername());
//        materialBorrowReturn.setUpdateTime(DateUtils.getNowDate());
//        materialBorrowReturn.setIsReturn(1);
//        materialBorrowReturnService.updateMaterialBorrowReturn(materialBorrowReturn);
//        //修改物料状态信息
//        MaterialDetial detial = materialDetialService.selectMaterialDetialByMaterialDetialId(materialBorrowReturn.getMaterialId());
//        detial.setStatus(DictUtils.getDictValue("sys_material_status","在库"));
//        detial.setCurrentPos(detial.getBeforePos());
//        detial.setUpdateTime(DateUtils.getNowDate());
//        detial.setUpdateBy(SecurityUtils.getLoginUser().getUsername());
//        materialDetialService.updateMaterialDetial(detial);
//        return success("归还成功");
//    }
}
